package com.ljd.hosp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ljd.cmn.feign.DictFeignClient;
import com.ljd.hosp.repository.HospitalRepository;
import com.ljd.hosp.service.HospitalService;
import com.ljd.yygh.model.hosp.Hospital;
import com.ljd.yygh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    HospitalRepository hospitalRepository;
    @Autowired
    DictFeignClient dictFeignClient;

    @Override
    public void save(Map<String, Object> paramMap) {
        // 把参数map集合转为hospital对象
        String mapJson = JSON.toJSONString(paramMap);
        Hospital hospital = JSON.parseObject(mapJson, Hospital.class);
        // 判断是否存在数据
        String hoscode = hospital.getHoscode();
        Hospital hosp =hospitalRepository.getHospitalByHoscode(hoscode);
        if(hosp!=null) {
            // 存在数据修改
            hospital.setStatus(hosp.getStatus());
            hospital.setCreateTime(hosp.getCreateTime());
        } else {
            // 不存在数据添加
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
        }
        hospital.setUpdateTime(new Date());
        hospital.setIsDeleted(0);
        hospitalRepository.save(hospital);
    }

    @Override
    public Hospital getHospitalByHoscode(String hoscode) {
        return hospitalRepository.getHospitalByHoscode(hoscode);
    }

    @Override
    public Page<Hospital> listHosp(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo,hospital);
        ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Example<Hospital> example = Example.of(hospital, matcher);
        Pageable pageable = PageRequest.of(page-1, limit);
        Page<Hospital> hospitalPage = hospitalRepository.findAll(example, pageable);
        hospitalPage.getContent().forEach(this::packHospital);
        return hospitalPage;
    }

    private void packHospital(Hospital hospital) {
        String hostypeString  = dictFeignClient.getName("Hostype", hospital.getHostype());
        String pCode = dictFeignClient.getName(hospital.getProvinceCode());
        String cCode = dictFeignClient.getName(hospital.getCityCode());
        String dCode = dictFeignClient.getName(hospital.getDistrictCode());
        hospital.getParam().put("hostypeString",hostypeString);
        hospital.getParam().put("fullAddress",pCode+cCode+dCode);
    }
}
